<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/24
 * Time: 19:14
 * Desc: 我的购物车
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\service\MycartService;
use app\index\service\WeixinService;

class MyCart extends Base{
    public function _initialize(){
        parent::_initialize();
        $cur_city = db('city')->where('key',cookie('city_key'))->value('value');        //当前城市

        $this->assign('realname',session('_user_uid_.realname'));
        $this->assign('cur_city',$cur_city);
        $this->assign('url',request()->url(true));      //我的购物车


    }

    /**
     * @Author  lingyun
     * @Desc    我的购物车 -- 购物车列表  当前门店购物车内的商品
     */
    public function my_cart(){
        $service = new MycartService();
        $service->my_cart();
        $service->get_header();             //获取公共头部信息
        $service->get_dapei_goods();        //获取底部搭配商品信息

        return $this->fetch('my_cart');
    }

    /**
     * @Author  lingyun
     * @Desc    减少购物车的商品购买数量
     */
    public function reduce_cart(){
        $service = new MycartService();
        $res = $service->reduce_cart();
        $res['code'] == 1?$this->success($res['msg'],'',['code'=>$res['code']]):$this->error($res['msg'],'',['code'=>$res['code']]);
    }

    /**
     * @Author  lingyun
     * @Desc    增加购物车的商品数量
     */
    public function increase_cart(){
        $service = new MycartService();
        $res = $service->increase_cart();
        $res['code']==1?$this->success($res['msg'],'',['code'=>$res['code']]):$this->error($res['msg'],'',['code'=>$res['code']]);
    }

    /**
     * @Author  lingyun
     * @Desc    删除购物车
     */
    public function del(){
        $service = new MycartService();
        $service->del();
    }

    /**
     * @Author  lingyun
     * @Desc    清空购物车
     * 2018-03-30
     */
    public function qingkong(){
        $service = new MycartService();
        $service->qingkong();
    }

    /**
     * @Author  lingyun
     * @Desc    提交结算前检查选中商品信息
     * 2018-04-28
     */
    public function check_cart(){
        $service = new MycartService();
        $this->update_cart();
        $service->check_cart();
    }

    /**
     * @Author  lingyun
     * @Desc    保存购物车
     *  [0] => array(9) {
    ["goods_id"] => string(3) "134"
    ["specid"] => string(4) "1226"
    ["goods_price"] => string(4) "0.01"
    ["goods_sum"] => string(1) "2"
    ["selected"] => string(1) "1"
    ["store_id"] => string(2) "13"
    ["goods_sum_price"] => string(4) "0.01"
    ["store_goods_stock_id"] => string(3) "417"
    ["addtime"] => string(10) "1531461746"
    }
     */
    public function update_cart(){
        $service = new MycartService();
        $store_id = cookie('store_id');
        $cart = cookie('user_cart');
        $my_cart = (array)cookie('user_cart');     //会员的购物车
//        $data = $service->filter_cart_data($my_cart);       //购物车
        $post = input('post.');
        foreach($cart as $k => $v){
            foreach($post['specs'] as $k1 => $v1){
                if($v1 == $v['specid'] && $v['store_id'] == $store_id){
                    $cart[$k]['goods_sum'] = $post['nums'][$k1];
                }
            }
        }
        cookie('user_cart',$cart,15552000);
        $this->success('成功','');
    }

    /**
     * @Author  lingyun
     * @Desc    生成订单
     */
    public function pre_create_order(){
        $service = new MycartService();
        $store_id = cookie('store_id');         //门店id
        $store = db('store')->where('id',$store_id)->field('id,is_jiameng,mobile,address')->find();
        $result = $service->pre_create_order();
        $this->assign('store_info',$store);
        if(!$result){
            return $this->fetch('public/error');
        }
        return $this->fetch('pre_create_order');

    }

    /**
     * @Author  lingyun
     * @Desc    支付订单
     */
    public function pay_order(){
        $service  = new MycartService();
        $post = input('post.');
        if(cookie('store_id') == ''){
            $this->assign('err_msg','您当前还没有选择门店，请先选择门店');
            $this->assign('err_url',url('Index/index'));
            $this->assign('err_button','选择门店');
            return $this->fetch('public/error');
            exit();
        }
        $uid = session('_user_uid_.uid');           //会员主键id
        if(empty($uid)){
            $this->assign('err_msg','您当前还没有登录，请先去登陆');
            $this->assign('err_url',url('Login/loginin'));
            $this->assign('err_button','登录');
            return $this->fetch('public/error');
            exit();
        }

        $service  =new MycartService();
        $result = $service->check_pay_order($post);

        if($result['code'] == 0){
            $this->assign('err_msg',$result['err_msg']);
            $this->assign('err_url',$result['err_url']);
            $this->assign('err_button',$result['err_button']);

            return $this->fetch('public/error');
        }

        if($post['pay_type'] == 1){             //支付宝支付
            $this->redirect(url('Alipay/pay').'?order_sn='.$result['order_sn']);
        }else if($post['pay_type'] == 2){       //微信支付
            $this->redirect(url('Weixinpay/weixin_pay').'?order_sn='.$result['order_sn']);
//            $this->redirect('Weixinpay/weixin_pay?order_sn='.$order_sn.'&final_amount='.$post['final_amount']);
        }else{                                  //余额支付
            $this->redirect(url('MyCart/pay_by_credit').'?order_sn='.$result['order_sn']);
        }

    }

    /**
     * @Author  lingyun
     * @Desc    使用余额进行支付
     * @param $order_sn     订单编号
     * @param $final_amount     最终支付金额
     */
    public function pay_by_credit(){
        $uid = session('_user_uid_.uid');
        $member = db('user')->where('uid',$uid)->field('uid,user_money,realname,openid')->find();
        $order_sn = input('order_sn');
        $order = db('order')->where('order_sn',$order_sn)->find();          //订单信息

        if(empty($order)){
            $this->assign('err_msg','找不到订单信息，请浏览其它商品重新下单');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','重新下单');
            return $this->fetch('public/error');
        }

        if($member['user_money'] < $order['final_amount']){
            $this->assign('err_msg','您的余额不足，请选择其它支付方式');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_url','重新支付');
            return $this->fetch('public/error');
        }

        if($order['pay_status'] == 0){          //未支付
            //构造余额支付记录数据
            $data_arr = [
                'uid'=>$uid,
                'admin_id'=>0,
                'store_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'order_sn'=>$order['order_sn'],
                'pay_time'=>time(),
                'pay_status'=>1,
                'pay_type'=>3,
                'amount'=>$order['final_amount'],
                'cur_amount'=>$member['user_money']-$order['final_amount'],
                'sign'=>2,
                'chargetype'=>1,
                'charge_cn'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                'addtime'=>time()
            ];
            //记录余额记录
            db('user_wallet_log')->data($data_arr)->insert();       //记录余额记录

            $pay_log_arr = [
                'order_id'=>$order['id'],
                'order_sn'=>$order['order_sn'],
                'order_type'=>1,
                'uid'=>$uid,
                'pay_type'=>3,
                'pay_sign'=>1,
                'store_id'=>$order['store_id'],
                'amount'=>$order['final_amount'],
                'remark'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                'addtime'=>time()
            ];
            db('pay_log')->data($pay_log_arr)->insert();            //记录支付记录

            //更新需要向门店进行转账的金额
            $store = db('store')->where('id',$order['store_id'])->find();
            $store_amount_arr = [
//                'credit'=>$store['credit']+$order['final_amount'],
//                'final_amount'=>$store['user_money']+$order['final_amount'],
                'user_money'=>$store['user_money']+$order['final_amount'],
            ];
            db('store')->where('id',$order['store_id'])->update($store_amount_arr);

            $cur_amount = $member['user_money'] - $order['final_amount'];    //会员当前的余额
            db('user')->where('uid',$uid)->update(['user_money'=>$cur_amount]);     //更新会员当前的余额
            db('order')->where('order_sn',$order_sn)->update(['pay_status'=>1,'pay_time'=>time(),'order_status'=>1,'remark'=>'已支付']);      //更新订单支付状态

            db('order_details')->where('order_id',$order['id'])->update(['status'=>1]);     //更新订单详情的支付状态

            //更新优惠券的使用情况
            db('user_ycard')->where('id',$order['coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
            db('user_ycard')->where('id',$order['cash_coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);

            //更新门店库存
            $order_details = db('order_details')->where('order_id',$order['id'])->select();
            foreach($order_details as $k => $v){
//                db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->setDec('stock',$v['goods_num']);
                $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                $cur_stock = $stock['stock'] - $v['goods_num'];
                //更新门店库存
                db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                $arr = [
                    'goods_id'=>$v['goods_id'],
                    'goods_spec_id'=>$stock['goods_spec_id'],
                    'title'=>$v['spec_detail'],
                    'order_id'=>$order['id'],
                    'store_id'=>$order['store_id'],
                    'ruku_num'=>0,
                    'tuihuo_num'=>0,
                    'chuku_num'=>$v['goods_num'],
                    'sunhao_num'=>0,
                    'remark'=>$order['order_sn'],
                    'cur_stock'=>$cur_stock,
                    'addtime'=>time()
                ];
                db('store_goods_log')->insert($arr);
            }

            //订单动作数据
            $data_action = [
                'uid'=>$uid,
                'order_id'=>$order['id'],
                'action_user'=>0,
                'order_status'=>1,
                'pay_status'=>1,
                'status_desc'=>'已支付，待发货',
                'storeid'=>$order['store_id'],
                'addtime'=>time()
            ];
            db('order_action')->data($data_action)->insert();       //新增订单数据

            //支付回调进行三级分销积分变更
            third_tier_distribution($uid,$order['final_amount'],$order['store_id'],$order['id'],0,$order['order_sn']);          //金更新积分，不更新会员的余额

            //存在会员的openid就推送模板消息
            if(!empty($member['openid'])){
                //推送模板消息
                $weixin_msg = [
                    "type"   	  =>1,
                    "touser" 	  =>$member["openid"],
                    "template_id"=>config("weixin_mu_msg.order_status")["tempid"],
                    "url" 		  =>request()->domain().url('Index/index'),
                    "topcolor"  =>"#743A3A",
                    "data"   =>[
                        "first" 	    =>["value"=>$order['order_sn']."订单支付成功",        		"color"=>"#743A3A"],
                        "keyword1"		=>["value"=>$order['final_amount'], 		"color"=>"#743A3A"],
                        "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                        "keyword3"		=>["value"=>"支付成功","color"=>"#743A3A"],
                        "remark"		=>["value"=>"您的订单已经支付成功，我们会尽快为您处理", 			"color"=>"#743A3A"],
                    ]
                ];
                $wein = new WeixinService();
                $rest  = $wein->sendmsg($weixin_msg);
            }
        }

        if($order['receive_coupon_id'] != ''){
            $this->assign('result',1);
        }else{
            $this->assign('result',0);
        }
        $service = new MyCartService();
        $service->get_header();             //获取顶部信息
//        halt($order['receive_coupon_id']);
        $my_coupon = db('user_ycard')->where(['uid'=>$uid,'store_id'=>cookie('store_id')])->column('coupon_id');
        $coupon = db('store_coupon')->where('id','in',trim($order['receive_coupon_id'],','))->select();
        $this->assign('coupon',$coupon);
        $this->assign('my_coupon',$my_coupon);
        $this->assign('receive_order_id',$order['id']);
        $this->assign('point',floor($order['final_amount']/2));
        return $this->fetch('zengsong_coupon');




        //支付成功，跳转至领取优惠券页面
        $this->success('支付成功',url('PayComplete/get_coupon')."?out_trade_no=".$order_sn,3);
    }


}